<?php
namespace FastPHP;

use FastPHP\Core\Router;
use FastPHP\Core\HttpException;

if (!defined('ROOT_PATH')) {
    define('ROOT_PATH', dirname(__DIR__) . '/');
}

class App
{
    public static function run($appPath)
    {
        // 1. 加载应用目录common.php
        $group = defined('APP_GROUP') ? APP_GROUP : (isset($_GET['s']) ? $_GET['s'] : 'home');
        $appCommon = $appPath . $group . '/app/common.php';
        if (file_exists($appCommon)) {
            require_once $appCommon;
        }

        require_once ROOT_PATH . 'FastPHP/Core/Router.php';

        try {
            // 路由统一解析
            $router = new Router();
            $group = $router->group;
            $controller = $router->controller;
            $action = $router->action;
            $_REQUEST = $_GET = $_POST = array_merge($_REQUEST, $router->params);

            // 将路由解析结果存储到全局变量中，供Controller和Request使用
            $GLOBALS['_ROUTER_GROUP'] = $group;
            $GLOBALS['_ROUTER_CONTROLLER'] = $controller;
            $GLOBALS['_ROUTER_ACTION'] = $action;
            $GLOBALS['_ROUTER_PARAMS'] = $router->params;

            $controllerClass = $group . '\\app\\controller\\' . ucfirst($controller);

            // 检查控制器是否存在
            if (class_exists($controllerClass)) {
                $ctrl = new $controllerClass();
                
                // 检查方法是否存在
                if (method_exists($ctrl, $action)) {
                    call_user_func([$ctrl, $action]);
                } else {
                    // 方法不存在，尝试调用_empty方法
                    if (method_exists($ctrl, '_empty')) {
                        call_user_func([$ctrl, '_empty'], $action);
                    } else {
                        throw new HttpException("方法 {$action} 不存在", 404);
                    }
                }
            } else {
                // 控制器不存在，尝试创建空控制器
                $emptyControllerClass = $group . '\\app\\controller\\EmptyController';
                if (class_exists($emptyControllerClass)) {
                    $ctrl = new $emptyControllerClass();
                    if (method_exists($ctrl, '_empty')) {
                        call_user_func([$ctrl, '_empty'], $controller, $action);
                    } else {
                        throw new HttpException("控制器 {$controllerClass} 不存在", 404);
                    }
                } else {
                    throw new HttpException("控制器 {$controllerClass} 不存在", 404);
                }
            }
        } catch (\Throwable $e) {
            \FastPHP\Core\ExceptionHandler::handle($e);
        }
    }
} 